#include "xdemux.h"
#include <iostream>
extern "C" {
#include "libavformat/avformat.h"
}
using namespace std;
static void PrintErr(int err) {
  char buf[1024] = {0};
  av_strerror(err, buf, sizeof(buf) - 1);
  cerr << buf << endl;
}

#define CERR(err)                                                              \
  if (err != 0) {                                                              \
    PrintErr(err);                                                             \
    return 0;                                                                  \
  }

AVFormatContext *XDemux::Open(const char *url) {
  AVFormatContext *c = nullptr;
  int ret = avformat_open_input(&c, url, nullptr, nullptr);
  CERR(ret);
  // 获取媒体信息
  ret = avformat_find_stream_info(c, nullptr);
  if (ret < 0) {
    avformat_close_input(&c);
  }
  av_dump_format(c, 0, url, 0);
  return c;
}

bool XDemux::Read(AVPacket *pkt) {
  unique_lock<mutex> lock(mux_);
  if (!c_)
    return false;
  auto re = av_read_frame(c_, pkt);
  CERR(re);
  return true;
}

bool XDemux::Seek(long long pts, int stream_index) {
  unique_lock<mutex> lock(mux_);
  if (!c_)
    return false;
  if (stream_index < 0 || stream_index >= c_->nb_streams)
    return false;
  // seek输入媒体问题 移动到第十秒的关键帧位置
  auto vs = c_->streams[stream_index];
  if (vs) {
    auto re = av_seek_frame(c_, vs->index, pts,
                            AVSEEK_FLAG_FRAME | AVSEEK_FLAG_BACKWARD);
    CERR(re);
    return true;
  }
  return false;
}
